const express = require('express');
const router = express.Router();
const mid = (req,res,next)=>{
    console.log('局部中间件1')
    next()
}
const mid2 = (req,res,next)=>{
    console.log('局部中间件2')
    next()
}
router.get('/',[mid,mid2],(req,res)=>{
    res.statusCode = 200
    res.setHeader('Content-Type','text/html;charset=utf-8')
    res.send(`<h1>首页</h1><a href="/api/user">用户列表</a>`)
})

function getUser(id){
    let users = [
        {id:1,name:'张三',reg_time:new Date()},
        {id:2,name:'你大爷',reg_time:new Date()},
        {id:3,name:'吊毛',reg_time:new Date()}
    ]
    if (id){
        return users.find(item=>item.id==id) || {}
    }
    return users
}

router.get('/user/:id',(req,res)=>{
    res.statusCode = 200
    // res.setHeader('Content-Type','text/html;charset=utf-8')
    let id = req.params['id']||null
    let user = getUser(id)
    user['startTime'] = req.startTime
    res.send(user)
})

router.get('/user',(req,res)=>{
    res.statusCode = 200
    // res.setHeader('Content-Type','text/html;charset=utf-8')
    let users = getUser()
    res.send(users)
})

router.post('/user',(req,res)=>{
    // 在服务器，可以使用 req.body 这个属性，来接收客户端发送过来的请求体数据
    // 默认情况下，如果不配置解析表单数据的中间件，则 req.body 默认等于 undefined
    console.log(req.body)
    res.statusCode = 200
    req.body['startTime'] = req.startTime
    req.body['status'] = 200
    // res.setHeader('Content-Type','text/html;charset=utf-8')
    res.send(req.body)
})

module.exports = router